<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAdd()">新增产品分类</el-button>

    <el-table
      class="table-container"
      :data="list"
      row-key="id"
      v-loading="listLoading"
      border
      :default-expanded-keys="expandedKey"
      :tree-props="{ children: 'children' }"
    >
      <el-table-column prop="name" label="菜单名称" header-align="center" />
      <el-table-column prop="productCount" label="商品数量" align="center" />
      <el-table-column prop="sort" label="排序" align="center" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.level < 1"
            size="mini"
            type="primary"
            @click="handleAdd(scope.row.id)"
            >增加子分类
          </el-button>
          <el-button size="mini" type="success" @click="handleUpdate(scope.row)"
            >编辑
          </el-button>
          <el-button
            v-if="!scope.row.children"
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getList"
    ></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from "./add-or-update";
import CategoryApi from "@/api/product/category";

export default {
  name: "Category",
  data() {
    return {
      list: [],
      listLoading: false,
      expandedKey: [],
      addOrUpdateVisible: false,
    };
  },
  components: {
    AddOrUpdate,
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      CategoryApi.getDataList().then((response) => {
        this.listLoading = false;
        this.list = response.data;
      });
    },
    //添加二级或三级分类
    handleAdd(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.initAdd(id);
      });
    },
    handleUpdate(row) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.initUpdate(row.id);
      });
    },
    handleDelete(row) {
      this.$confirm(`是否删除【${row.name}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          CategoryApi.deleteCategory(row.id).then(({ data }) => {
            this.$message({
              message: "菜单删除成功",
              type: "success",
            });
            this.getList();
            //设置需要默认展开的菜单
            this.expandedKey = [row.parentId];
          });
        })
        .catch(() => {});
    },
  },
};
</script>
